<?php
namespace app\api\controller;

use app\admin\model\identity\Identity;
use app\admin\model\system\System;
use app\common\controller\Api;
use PHPMailer\PHPMailer\PHPMailer;
use think\Db;
use think\Exception;

class Recharge extends Api{
    protected $noNeedLogin = ['getidentitylist','getqrimg'];
    protected $noNeedRight = ['*'];

    public function getidentitylist(){
        $identityModel = new Identity();
        $where['id']=['neq',4];
        $list = collection($identityModel->where($where)->field('id,name,price')->select())->toArray();
        $newlist=[];
        foreach ($list as $k=>$v){
            $newlist[$k]['identity_id']=$v['id'];
            $newlist[$k]['name']=$v['name'];
            $newlist[$k]['price']=$v['price'];
            if($v['id']==5){
                $newlist[$k]['unit']=2;
            }else{
                $newlist[$k]['unit']=1;
            }
        }
        $this->success('成功',$newlist);
    }

    public function upimg(){
        $img = $this->request->param('img');
        $id = $this->request->param('id');
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $rechargeModel->where(['id'=>$id])->update(['img'=>$img]);
        $this->success('成功');
    }

    public function getdetail(){
        $id = $this->request->param('id');
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $info=$rechargeModel->where(['id'=>$id])->find()->toArray();
        $this->success('成功',$info);
    }

    public function getqrimg(){
        $systemModel = new System();
        $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
        $this->success('成功',[
            'qrimg'=>'http://47.239.156.92'.$systeminfo['usdt_img'],
            'usdt_address'=>$systeminfo['usdt_address'],
            'trc_img'=>'http://47.239.156.92'.$systeminfo['trc_img'],
            'trc_address'=>$systeminfo['trc_address'],
            'wx_img'=>'http://47.239.156.92'.$systeminfo['wx_img'],
            'zfb_img'=>'http://47.239.156.92'.$systeminfo['zfb_img'],
            'name'=>$systeminfo['name'],
            'card'=>$systeminfo['card'],
            'shenghuo'=>'http://47.239.156.92'.$systeminfo['shenghuo']
            ]);
    }

    /*public function apply(){
        $price = $this->request->param('price');
        $img = $this->request->param('img');
        $tongdao =$this->request->param('tongdao');
        $province = $this->request->param('province');
        $city = $this->request->param('city');
        $district = $this->request->param('district');
        if(!$tongdao || $tongdao==''){
            $tongdao=1;
        }
        $unit = 2;

        if(!$price || !$unit){
            $this->error('提交的参数缺失');
        }
        $userinfo = $this->auth->getUserinfo();
        if($province==''){
            $province=$userinfo['province'];
        }
        if($city==''){
            $city=$userinfo['city'];
        }
        if($district==''){
            $district=$userinfo['district'];
        }
        if($userinfo['is_freeze']==1){
            $this->error('您的帐户被冻结，不能充值');
        }
        //查一下是否有申请中的充值
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $rechargeinfo = $rechargeModel->where(['user_id'=>$userinfo['id'],'status'=>0])->find();
        if($rechargeinfo){
            $this->error('您有正在申请中的充值，请不要重复提交');
        }
        if($unit==1){
            $unit_name = '数字人民币';
        }else{
            $unit_name = 'USDT';
        }

        //提交充值，待审
        $indata['user_id'] = $userinfo['id'];
        $indata['amount'] = $price;
        $indata['unit'] = $unit;
        $indata['unit_name'] = $unit_name;
        $indata['event'] = '用户'.$userinfo['nickname'].'申请充值'.$price.$unit_name;
        $indata['create_time'] = time();
        $indata['img'] = $img;
        $indata['tongdao'] = $tongdao;
        $indata['province'] = $province;
        $indata['city'] = $city;
        $indata['district'] = $district;
        $ret = $rechargeModel->insertGetId($indata);
        if($ret){
            //给管理员邮箱发消息提醒
            $systemModel = new System();
            $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
            if($systeminfo!=''){
                $arr=explode(",",$systeminfo['email']);
                $mail = new PHPMailer(true);

                // 服务器配置 - 使用587端口
                $mail->isSMTP();
                $mail->Host = 'smtp.qq.com';
                $mail->SMTPAuth = true;
                $mail->Username = '309913834@qq.com';
                $mail->Password = 'gtmtppbcslrqbjeg';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 使用STARTTLS
                $mail->Port = 587; // 587端口

                // 编码设置
                $mail->CharSet = 'UTF-8';
                $mail->SMTPOptions = array(
                    'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    )
                );
                if(count($arr)==1){
                    // 发件人配置
                    $mail->setFrom('309913834@qq.com', '合创城');
                    $mail->addAddress($arr[0]);

                    // 邮件内容
                    $mail->isHTML(true);
                    $mail->Subject = '用户充值提醒';
                    $mail->Body = '用户'.$userinfo['id'].'申请充值'.$price.$unit_name.'请尽快审核';
                    $mail->AltBody = "用户充值提醒";

                    $mail->send();
                }else{
                    foreach ($arr as $k=>$v){
                        // 发件人配置
                        $mail->setFrom('309913834@qq.com', '合创城');
                        $mail->addAddress($v);

                        // 邮件内容
                        $mail->isHTML(true);
                        $mail->Subject = '用户充值提醒';
                        $mail->Body = '用户'.$userinfo['id'].'申请充值'.$price.$unit_name.'请尽快审核';
                        $mail->AltBody = "用户充值提醒";

                        $mail->send();
                    }
                }
            }
            $this->success('充值成功，请等待管理员审核',['id'=>$ret]);
        }else{
            $this->error('充值失败');
        }
    }*/

    public function apply(){
        $price = $this->request->param('price');
        $img = $this->request->param('img');
        $tongdao =$this->request->param('tongdao');
        $province = $this->request->param('province');
        $city = $this->request->param('city');
        $district = $this->request->param('district');
        if(!$tongdao || $tongdao==''){
            $tongdao=1;
        }
        if(!$price){
            $this->error('请输入充值金额');
        }
        $userinfo = $this->auth->getUserinfo();
        if($province==''){
            $province=$userinfo['province'];
        }
        if($city==''){
            $city=$userinfo['city'];
        }
        if($district==''){
            $district=$userinfo['district'];
        }
        if($userinfo['is_freeze']==1){
            $this->error('您的帐户被冻结，不能充值');
        }
        if($tongdao==3 || $tongdao==4 || $tongdao==5 || $tongdao ==7){
            $systemModel = new System();
            $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
            $chong_price = $price;
            $unit = 1;
            $unit_name = '人民币';
        }else if($tongdao==1 || $tongdao==2){
            $chong_price = $price;
            $unit = 2;
            $unit_name = 'USDT';
        }else if($tongdao==6){
            if($price>$userinfo['shouyi_balance']){
                $this->error('余额不足');
            }
            $systemModel = new System();
            $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
            $chong_price = $price;
            $unit = 1;
            $unit_name = 'HC';
        }
        //查一下是否有申请中的充值
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $rechargeinfo = $rechargeModel->where(['user_id'=>$userinfo['id'],'status'=>0])->find();
        if($rechargeinfo){
            $this->error('您有正在申请中的充值，请不要重复提交');
        }

        if($tongdao==6){
            //先扣掉用户的余额
            $userModel = new \app\admin\model\User();
            $userModel->where(['id'=>$userinfo['id']])->setDec('shouyi_balance',$price);
            //提交充值，待审
            $indata['user_id'] = $userinfo['id'];
            $indata['amount'] = $chong_price;
            $indata['unit'] = $unit;
            $indata['unit_name'] = $unit_name;
            $indata['event'] = '用户'.$userinfo['nickname'].'申请充值'.$price.$unit_name;
            $indata['create_time'] = time();
            $indata['img'] = $img;
            $indata['tongdao'] = $tongdao;
            $indata['province'] = $province;
            $indata['city'] = $city;
            $indata['district'] = $district;
            $ret = $rechargeModel->insertGetId($indata);
        }else{
            //提交充值，待审
            $indata['user_id'] = $userinfo['id'];
            $indata['amount'] = $chong_price;
            $indata['unit'] = $unit;
            $indata['unit_name'] = $unit_name;
            $indata['event'] = '用户'.$userinfo['nickname'].'申请充值'.$price.$unit_name;
            $indata['create_time'] = time();
            $indata['img'] = $img;
            $indata['tongdao'] = $tongdao;
            $indata['province'] = $province;
            $indata['city'] = $city;
            $indata['district'] = $district;
            $ret = $rechargeModel->insertGetId($indata);
        }
        if($ret){
            //给管理员邮箱发消息提醒
            $systemModel = new System();
            $systeminfo = $systemModel->where(['id'=>1])->find()->toArray();
            if($systeminfo['email']!='') {
                $emailList = explode(",", $systeminfo['email']);
                $emailList = array_filter(array_map('trim', $emailList));

                // 初始化 PHPMailer
                $mail = new PHPMailer(true);

                // 服务器配置（只需设置一次）
                $mail->isSMTP();
                $mail->Host = 'smtp.qq.com';
                $mail->SMTPAuth = true;
                $mail->Username = '3906570020@qq.com';
                $mail->Password = 'ynfxafymcczicejf';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port = 587;
                $mail->CharSet = 'UTF-8';
                $mail->SMTPOptions = array(
                    'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    )
                );

                $successCount = 0;
                $failCount = 0;
                $failEmails = [];

                foreach ($emailList as $email) {
                    if (!$this->checkemail($email)) {
                        $failCount++;
                        $failEmails[] = $email . '(格式无效)';
                        continue;
                    }

                    try {
                        // 清理之前的收件人
                        $mail->clearAddresses();
                        $mail->clearCCs();
                        $mail->clearBCCs();
                        $mail->clearReplyTos();
                        $mail->clearAllRecipients();
                        $mail->clearAttachments();
                        $mail->clearCustomHeaders();

                        // 设置新的收件人
                        $mail->setFrom('3906570020@qq.com', '合创城');
                        $mail->addAddress($email);

                        // 邮件内容
                        $mail->isHTML(true);
                        $mail->Subject = '用户充值提醒';
                        $mail->Body = '用户'.$userinfo['id'].'申请充值'.$price.'请尽快审核';
                        $mail->AltBody = "用户充值提醒";

                        if ($mail->send()) {
                            $successCount++;
                        } else {
                            $failCount++;
                            $failEmails[] = $email;
                        }
                    } catch (Exception $e) {
                        $failCount++;
                        $failEmails[] = $email . '(' . $e->getMessage() . ')';
                    }

                    // 短暂延迟
                    usleep(100000);
                }
            }
            $this->success('充值成功，请等待管理员审核',['id'=>$ret]);
        }else{
            $this->error('充值失败');
        }
    }

    public function checkemail($email){
        return filter_var(trim($email), FILTER_VALIDATE_EMAIL) !== false;
    }

    public function rechargelist(){
        $userinfo = $this->auth->getUserinfo();
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $list = collection($rechargeModel->where(['user_id'=>$userinfo['id'],'isdeleted'=>0])->select());
        if($list){
            $list = $list->toArray();
            $newlist=[];
            foreach ($list as $k=>$v){
                $newlist[$k]['id']=$v['id'];
                $newlist[$k]['amount']=$v['amount'];
                $newlist[$k]['unit_name']=$v['unit_name'];
                $newlist[$k]['create_time']=date("Y-m-d H:i:s",$v['create_time']);
                $newlist[$k]['event']=$v['event'];
                if($v['status']==0){
                    $newlist[$k]['status_name']='待审核';
                }else if($v['status']==1){
                    $newlist[$k]['status_name']='充值成功';
                }else if($v['status']==2){
                    $newlist[$k]['status_name']='充值失败';
                }
                $newlist[$k]['status']=$v['status'];
                $newlist[$k]['reason']=$v['reason'];
            }
            $this->success('成功',$newlist);
        }else{
            $this->success('成功',[]);
        }
    }

    public function tui(){
        $id = $this->request->param('id');
        $userinfo =$this->auth->getUserinfo();
        $rechargeModel = new \app\admin\model\recharge\Recharge();
        $info = $rechargeModel->where(['id'=>$id])->find()->toArray();
        if($info['user_id'] != $userinfo['id']){
            $this->error('您只能撤回自己的充值！');
        }
        if($info['status']!=0){
            $this->error('不是审核中的状态，不能撤回');
        }
        if($info['tongdao']==6){
            Db::startTrans();
            try{
                $userModel = new \app\admin\model\User();
                $userModel->where(['id'=>$userinfo['id']])->setInc('shouyi_balance',$info['amount']);

                $rechargeModel->where(['id'=>$id])->update(['is_deleted'=>1,'status'=>3]);
                Db::commit();
                $this->success('撤回成功');
            }catch(Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
        }else{
            $rechargeModel->where(['id'=>$id])->update(['is_deleted'=>1,'status'=>3]);
            $this->success('撤回成功');
        }
    }
}